//
//  goodsItem.swift
//  uiKit-demo
//
//  Created by 陈澎 on 2025/1/23.
//

import UIKit
import Kingfisher

class GoodsItemViewCell: UITableViewCell {
    let titleLabel: UILabel = {
        let title = UILabel()
        title.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        title.numberOfLines = 2
        title.translatesAutoresizingMaskIntoConstraints = false
        return title
    }()
    
    let subTitleLabel: UILabel = {
        let subTItle = UILabel()
        subTItle.numberOfLines = 1
        subTItle.textColor = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
        subTItle.font = UIFont.systemFont(ofSize: 12)
        subTItle.translatesAutoresizingMaskIntoConstraints = false
        return subTItle
    }()
    let goodsImgView: UIImageView = {
        let goodsImgView = UIImageView()
        goodsImgView.frame = CGRect(x: 0, y: 0, width: ScaleBasedScene.getFinalSizeVal(110), height: ScaleBasedScene.getFinalSizeVal(110))
        return goodsImgView
    }()
    let intPriceLabel: UILabel = {
        let curPriceLabel = UILabel()
        curPriceLabel.font = UIFont.systemFont(ofSize: ScaleBasedScene.getFinalSizeVal(18))
        curPriceLabel.textColor = UIColor(red: 1, green: 0.16, blue: 0.16, alpha: 1)
        return curPriceLabel
    }()
    
    let demicalPriceLabel: UILabel = {
        let demicalPriceLabel = UILabel()
        demicalPriceLabel.font = UIFont.systemFont(ofSize: ScaleBasedScene.getFinalSizeVal(12))
        demicalPriceLabel.textColor = UIColor(red: 1, green: 0.16, blue: 0.16, alpha: 1)
        return demicalPriceLabel
    }()
    let unitPriceLabel: UILabel = {
        let unitPriceLabel = UILabel()
        unitPriceLabel.textColor = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
        unitPriceLabel.font = UIFont.systemFont(ofSize: ScaleBasedScene.getFinalSizeVal(10))  // 设置字体大小
        return unitPriceLabel
    }()
    let linePriceLabel: UILabel = {
        let linePriceLabel = UILabel()
        linePriceLabel.textColor = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
        linePriceLabel.font = UIFont.systemFont(ofSize: ScaleBasedScene.getFinalSizeVal(10))  // 设置字体大小
        return linePriceLabel
    }()
    override init(style: UITableViewCell.CellStyle, reuseIdentifier reuseIndentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIndentifier)
        let leftView = UIView()
        leftView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(leftView)
        NSLayoutConstraint.activate([
            leftView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: ScaleBasedScene.getFinalSizeVal(12)),
            leftView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: ScaleBasedScene.getFinalSizeVal(10)),
            leftView.widthAnchor.constraint(equalToConstant: ScaleBasedScene.getFinalSizeVal(110)),
            leftView.heightAnchor.constraint(equalToConstant: ScaleBasedScene.getFinalSizeVal(110))
        ])
        leftView.addSubview(goodsImgView)
        
        let rightView = UIView()
        rightView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(rightView)
        NSLayoutConstraint.activate([
            rightView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: ScaleBasedScene.getFinalSizeVal(10)),
            rightView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0),
            rightView.leadingAnchor.constraint(equalTo: leftView.trailingAnchor, constant:ScaleBasedScene.getFinalSizeVal(11)),
            rightView.widthAnchor.constraint(equalTo: contentView.widthAnchor, multiplier: ScaleBasedScene.getRelativeScale(parentW: contentView.bounds.width, curW: 243)),
            rightView.heightAnchor.constraint(equalToConstant: 134)
        ])
        
        rightView.addSubview(titleLabel)
        rightView.addSubview(subTitleLabel)
        
        let footerView = UIStackView()
        footerView.axis = .horizontal
        footerView.alignment = .center
        
        /**
             .fill：子视图充满整个堆叠视图。
             .fillEqually：子视图在堆叠中占用相同的空间。
             .fillProportionally：子视图占用的空间根据它们的内容大小自动调整。
             .equalSpacing：子视图之间的间隔相等，剩余空间平均分配。
             .equalCentering：子视图之间的间距相等，且子视图居中。
         */
        footerView.distribution = .fill
        footerView.translatesAutoresizingMaskIntoConstraints = false
        rightView.addSubview(footerView)
        
        let priceSymbol = UILabel()
        priceSymbol.text = "¥"  // 羊角符号
        priceSymbol.textColor = UIColor(red: 1, green: 0.16, blue: 0.16, alpha: 1)
        priceSymbol.font = UIFont.systemFont(ofSize: ScaleBasedScene.getFinalSizeVal(12))  // 设置字体大小
        priceSymbol.textAlignment = .center
        
        let priceView = UIStackView()
        priceView.axis = .horizontal
        priceView.alignment = .bottom
        // 子视图占用的空间根据它们的内容大小自动调整。
        priceView.distribution = .fill
        priceView.translatesAutoresizingMaskIntoConstraints = false
        priceView.addArrangedSubview(priceSymbol)
        priceView.addArrangedSubview(intPriceLabel)
        priceView.addArrangedSubview(demicalPriceLabel)
        priceView.addArrangedSubview(unitPriceLabel)
        priceView.addArrangedSubview(linePriceLabel)
        
        // 加入购物车
        let addCartView = UIView()
        let cartImage = UIImage(named: "cart")
        let addCartImg = UIImageView(image: cartImage)
        addCartView.addSubview(addCartImg)
        addCartImg.translatesAutoresizingMaskIntoConstraints = false
        addCartView.translatesAutoresizingMaskIntoConstraints = false
        let onAddCart = UITapGestureRecognizer(target: self, action: #selector(addCartHandle))
        addCartView.addGestureRecognizer(onAddCart)
       
        footerView.addArrangedSubview(priceView)
        footerView.addArrangedSubview(addCartView)
        
        NSLayoutConstraint.activate([
            titleLabel.trailingAnchor.constraint(equalTo: rightView.trailingAnchor, constant: 0),
            titleLabel.widthAnchor.constraint(equalTo: rightView.widthAnchor, multiplier: 1),
//            titleLabel.heightAnchor.constraint(equalToConstant: 40)
            
            subTitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: ScaleBasedScene.getFinalSizeVal(5.5)),
            subTitleLabel.heightAnchor.constraint(equalToConstant: ScaleBasedScene.getFinalSizeVal(17)),
            subTitleLabel.widthAnchor.constraint(equalTo: rightView.widthAnchor, multiplier: 1),
//            subTitleLabel.trailingAnchor.constraint(equalTo: rightView.trailingAnchor),
            
            footerView.bottomAnchor.constraint(equalTo: rightView.bottomAnchor, constant: -ScaleBasedScene.getFinalSizeVal(13)),
            footerView.heightAnchor.constraint(equalToConstant: ScaleBasedScene.getFinalSizeVal(24)),
            footerView.widthAnchor.constraint(equalTo: rightView.widthAnchor, multiplier: 1),
            
            addCartImg.centerXAnchor.constraint(equalTo: addCartView.centerXAnchor),
            addCartImg.centerYAnchor.constraint(equalTo: addCartView.centerYAnchor)

        ])

        priceView.setContentHuggingPriority(.defaultLow, for: .horizontal)
        priceView.setContentCompressionResistancePriority(.required, for: .horizontal) // 防止被压缩
        
        addCartView.setContentHuggingPriority(.required, for: .horizontal)
        addCartView.setContentCompressionResistancePriority(.required, for: .horizontal) // 防止被压缩
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    @objc func addCartHandle() {
        print("添加购物车")
    }
    func configure(data: VoucherGoodsRes.MercgabduseListItem) {
        titleLabel.text = data.sm_name
        subTitleLabel.text = data.subtitle
        // 处理商品图
        if let url = data.sm_pic {
            let goodsImgUrl = URL(string: url)
            goodsImgView.kf.setImage(with: goodsImgUrl, placeholder: UIImage(named: "bgLogo"))
        }
        // 处理价格
        if let sm_price = data.sm_price {
            let priceFormat = splitDecimal(sm_price)
            if let intPrice = priceFormat["int"] {
                intPriceLabel.text = "\(intPrice)"
            }
            if let floatPrice = priceFormat["float"] {
                demicalPriceLabel.text = "\(floatPrice)"
            }
        }
        // 处理价格单位
        if let saleUnit = data.sale_unit, !saleUnit.isEmpty {
            unitPriceLabel.text = "/\(saleUnit)"
        }
        // 处理划线价
        if let it_mprice = data.it_mprice, !it_mprice.isEmpty {
            linePriceLabel.text = "¥\(it_mprice)"
        }
        
    }
    // 字典：[String: String]
    func splitDecimal(_ buyPrice: String) -> [String: String] {
        var priceVal = [String: String]()

        let components = buyPrice.components(separatedBy: ".")
        let intPrice = components.first ?? ""
        let floatPrice = components.last ?? ""
        priceVal["int"] = !floatPrice.isEmpty ? "\(intPrice)." : intPrice
      
        priceVal["float"] = String(floatPrice)
        return priceVal
    }
}
// firstIndex：获取匹配第一个符合条件的下标
//        let pointIndex = buyPrice.firstIndex(of: ".")
//        let buyPriceEndIdx = buyPrice.endIndex
//        let intEndIndex = pointIndex ?? buyPriceEndIdx
        // buyPrice[..<intEndIndex]获取的是一种子字符串实例，与字符串不同；需要转译成String
//        let intPrice = String(buyPrice[..<intEndIndex])
